document.addEventListener('DOMContentLoaded', () => {
    const folderTree = document.getElementsByClassName('folder-tree')[0];
    const fileList = document.getElementsByClassName('file-list')[0];
    const previewDiv = document.getElementsByClassName('preview')[0];
    const preImageDiv = document.querySelector('#one-img');
    const longImageDiv = document.querySelector('#long-img');
    const scrollContent = document.getElementById('tab_a_plan');
	const titleSpan = document.getElementById('av-title');
	const flagSpan = document.getElementById('av-flag');
	const ciliPanel = document.getElementById('cili_panel');
	
	const searchTxt = document.getElementById('code-search');
	const historyList = document.getElementById('historyList');
	const clearSearchBtn = document.getElementById('clear-search-btn');
	const delSearchBtn = document.getElementById('del-search-btn');

    const info_panel = document.querySelector('.movie-info-panel');
    const label_code = info_panel.querySelector('.lable-code span');
    const label_ri = info_panel.querySelector('.lable-ri span');
    const label_zh = info_panel.querySelector('.label-zh span');
    const label_shic = info_panel.querySelector('.lable-shic span');
    const label_yany = info_panel.querySelector('.lable-yany span');
    const label_jies = info_panel.querySelector('.lable-jies p');

    const copyRiBtn = info_panel.querySelector('.copy-ri');
    const copyZhBtn = info_panel.querySelector('.copy-zh');
    const  addBookmarkBtn = info_panel.querySelector('#add_bookmark');
	const randmBtn = document.getElementById('randm_btn');
	const randmPlayBtn = document.getElementById('randm_play_btn');

    const coverImg = document.querySelector('.av-cover');
    const coverBtn = document.querySelector('.cover-btn');

    let selItem = null;
    let selFolder = null;
    let selBookmark = null;
    let selTabIndex = 1;
    let selAvUrl = null;
    let selNodes = null;
    let randmNodes = {};

    // ******************************************************************************************************************************************************
    //#region tree
    // Function to build the folder tree
    function findDestFolder(bookmarks, parentId = 0) {
        let destBookmark = null;

        for (let bookmark of bookmarks) {
            if (bookmark.title.includes("av-old")) {
                destBookmark = bookmark;
                break;
            }

            if (bookmark.children) {
                destBookmark = findDestFolder(bookmark.children, bookmark.id);
                if (destBookmark) {
                    break;
                }
            }
        }

        return destBookmark;
    }

    function createFolderElement(bookmark, parentId) {
        const li = document.createElement('li');
        li.classList.add('folder');
        li.textContent = bookmark.title;
        li.dataset.id = bookmark.id;
        li.dataset.parentId = parentId;

        li.addEventListener('dblclick', function (event) {
            const chilUl = li.querySelector('ul');

            if (chilUl) {
                li.removeChild(chilUl);
            } else {
                childUl = buildFolderTree(bookmark.children, bookmark.id);
                li.appendChild(childUl);
            }

            event.stopPropagation();
        });

        li.addEventListener('click', (event) => {
            if (selFolder) {
                selFolder.style.removeProperty('background-color');
            }
            selFolder = li;
            selFolder.style.backgroundColor = '#d58282';

            queryBookmarkList(bookmark.id);

            event.stopPropagation();
        });

        return li;
    }

    function isExpandClass(bookmarks) {
        for (let bookmark of bookmarks) {
            if (bookmark.children) {
                return true;
            }
        }

        return false;
    }

    function createFolderElement2(bookmark, parentId) {
        const div = document.createElement('div');
        div.classList.add('tree-row');
        div.dataset.id = bookmark.id;
        div.dataset.parentId = parentId;

        const expand = document.createElement('span');
        expand.classList.add('expand');
        expand.addEventListener('click', function (event) {
            const chilUl = div.querySelector('div');

            if (chilUl) {
                div.removeChild(chilUl);
                expand.style.transform = 'rotate(-90deg)';
            } else {
                childUl = buildFolderTree2(bookmark.children, bookmark.id);
                div.appendChild(childUl);
                expand.style.transform = 'rotate(0)';
            }

            event.stopPropagation();
        });
        div.appendChild(expand);
        if (isExpandClass(bookmark.children)) {
            expand.style.visibility = 'visible';
        } else {
            expand.style.visibility = 'hidden';
        }

        const lable = document.createElement('span');
        lable.classList.add('folder');
        lable.textContent = bookmark.title;
        div.appendChild(lable);

        div.addEventListener('dblclick', function (event) {
            const chilUl = div.querySelector('div');

            if (chilUl) {
                div.removeChild(chilUl);
                expand.style.transform = 'rotate(-90deg)';
            } else {
                childUl = buildFolderTree2(bookmark.children, bookmark.id);
                div.appendChild(childUl);
                expand.style.transform = 'rotate(0)';
            }

            event.stopPropagation();
        });

        div.addEventListener('click', (event) => {
            if (selFolder) {
                let lable = selFolder.querySelector('.folder');
                lable.style.removeProperty('background-color');
            }
            selFolder = div;
            let lable = selFolder.querySelector('.folder');
            lable.style.backgroundColor = '#d58282';

            queryBookmarkList(bookmark.id);

            event.stopPropagation();
        });

        return div;
    }

    function buildFolderTree2(bookmarks, parentId = 0) {
        const ul = document.createElement('div');
        ul.classList.add('tree-children');
        bookmarks.forEach(bookmark => {
            if (bookmark.children) {
                const li = createFolderElement2(bookmark, parentId);

                ul.appendChild(li);
            }

        });
        return ul;
    }

    function buildFolderTree(bookmarks, parentId = 0) {
        const ul = document.createElement('ul');
        bookmarks.forEach(bookmark => {
            if (bookmark.children) {
                const li = createFolderElement(bookmark, parentId);

                ul.appendChild(li);
            }

        });
        return ul;
    }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region list

    let inputTimer = null;

    function searchBookmarkList(searchStr) {
        chrome.bookmarks.search(searchStr, (nodes) => {
            updateFileList(nodes);
            selNodes = nodes;
        });
    }

    function queryBookmarkList(folderId) {
        chrome.bookmarks.getSubTree(folderId, (nodes) => {
            updateFileList(nodes[0].children);
            selNodes = nodes;
        });
    }

    // Function to update the file list
    function updateFileList(nodes) {
        fileList.innerHTML = '';

        nodes.forEach(bookmark => {
            if (bookmark.children) return;

            const bookmarkTitle2 = bookmark.title.replace(".HD", "").replace(".FHD", "").replace(".txt", "").replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/g, '');
            const regex = /[a-zA-Z]{2,5}-?[0-9]{2,5}/;
            const match = bookmarkTitle2.match(regex);
            let avcode = null;
            if (match && match[0]) {
                avcode = match[0].toLowerCase();
            }

            if (!avcode) return;

            const li = document.createElement('li');
            // li.textContent = bookmark.title;
            li.dataset.id = bookmark.id;

            let splitArr = splitSpan(bookmark.title);
            if (splitArr.length > 1) {
                const spanCode = document.createElement('span');
                spanCode.style.color = '#42af1c';
                spanCode.style.fontSize = "90%";
                spanCode.textContent = splitArr[0];
                li.appendChild(spanCode);

                const spanName = document.createElement('span');
                spanName.style.color = '#186060';
                spanName.style.fontSize = "110%";
                spanName.textContent = splitArr[1];
                li.appendChild(spanName);

                const spanStar = document.createElement('span');
                spanStar.style.color = '#6d6dda';
                spanStar.style.fontSize = "90%";
                spanStar.textContent = splitArr[2];
                li.appendChild(spanStar);
            } else {
                li.textContent = bookmark.title;
            }

            let javicon = 'other.png';
            if (bookmark.url.includes('anxia') || bookmark.url.includes('115vod')) {
                javicon = 'anxia.png';
            } else if (bookmark.url.includes('bus')) {
                javicon = 'bus.png';
            } else if (bookmark.url.includes('javdb')) {
                javicon = 'javdb.png';
            }

            li.style = `
                // background-image: url(chrome://favicon/size/16@1x/${bookmark.url});
                background-image: url(icons/${javicon});
                background-repeat: no-repeat;
                background-size: 16px;
            `;

            li.addEventListener('click', () => {
                if (selItem) {
                    selItem.style.removeProperty('background-color');
                }
                selItem = li;
                selItem.style.backgroundColor = '#e7caca';

				let titleInfo = "【目录：" + bookmark.folder + "】 " + bookmark.title;
                previewBookmark(selTabIndex, bookmark.title, titleInfo);
            });

            li.addEventListener('dblclick', () => {
                let url = bookmark.url;
                if (url.includes('bus') || url.includes('javdb')) {
                    let codeText2 = formatCodeForNone(avcode);
                    let url = `https://webapi.115.com/files/search?search_value=${codeText2}&format=json`;
                    var newWindow = window.open(url, '_blank'); // 在新标签页中打开URL

				} else if (url.includes('anxia')) {
					url = url.replace('v.anxia.com', '115vod.com');
					window.open(url);
					
                } else if (url.includes('115vod')) {
                    window.open(url);

                } else {
                    window.open(url);

                }


            });

            fileList.appendChild(li);
        });
    }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region content
    function previewBookmark(selTab, bookmarkTitle, titleStr='none title', avUrl=null) {
        if (titleStr) {
            titleSpan.textContent = titleStr;
        }
        selAvUrl = avUrl;

        const bookmarkTitle2 = bookmarkTitle.replace(".HD", "").replace(".FHD", "").replace(".txt", "").replace(/[a-zA-Z0-9]+\.[a-zA-Z]{2,3}/g, '');
        // 使用正则表达式匹配文件名
        const regex = /[a-zA-Z]{2,5}-?[0-9]{2,5}/;
        const match = bookmarkTitle2.match(regex);
        let avcode = null;
        // const previewUrl = 'https://www.cd120.com.cn/thumb/assets/addons/cms/img/noimage/503/288.jpg';
        let previewUrl = `http://localhost:10168/preview/defult.jpg`;

        // 如果找到匹配项，将其作为键存入 Map
        // 注意：这里我们假设每个匹配的文件名都是唯一的，或者我们只关心第一个匹配项
        if (match && match[0]) {
            avcode = match[0].toLowerCase();
        }

        if (!avcode) return;
        let newCode = formatCode(avcode);

        startRequest(avcode, "插件");

        if (selBookmark != bookmarkTitle) {
            // 增加预览视频
            // let videoSrc = "https://fivetiu.com/" + newCode + "/preview.mp4";
            let videoSrc = "https://fourhoi.com/" + newCode + "/preview.mp4";
            let preVideo = previewDiv.querySelector('#pre-video');
            preVideo.src = videoSrc;

            // 增加预览图
            // let imgSrc = "https://pedia-bucket-image.xfuse.fun/covers/" + newCode.toUpperCase() + ".jpg";
            let imgSrc = "https://fourhoi.com/" + newCode.toLowerCase() + "/cover-n.jpg";
            let img = previewDiv.querySelector('#pre-img');
            img.style.width = '100%';
            img.src = imgSrc;

            coverImg.src = imgSrc;

            searchFileFlag(newCode, function (ret, flag){
                if (ret == 0){
                    flagSpan.textContent = `【${flag}】`;
                }
            });
        }
        selBookmark = bookmarkTitle;
        selTabIndex = selTab;

        if (selTab == 1){
            // 增加预览图
            ciliPanel.classList.add('hide');
            preImageDiv.classList.remove('hide');
            preImageDiv.innerHTML = '';
            ciliPanel.innerHTML = '';
            searchFileList_javbus(newCode, 'preview', preImgCallback, finishCallback, infoCallback);

        }else if (selTab == 2){
            // 增加预览图
            ciliPanel.classList.remove('hide');
            preImageDiv.classList.remove('hide');
            preImageDiv.innerHTML = '';
            ciliPanel.innerHTML = '';
            searchFileList_javdb(newCode, 'preview', preImgCallback, finishCallback, infoCallback, ciliCallback);

            // let searchCode = formatCodeForNone(newCode);
            // ciliPanel.src = 'https://qjkkuqvc.2048173.xyz/search-' + searchCode + '-0-0-1.html'
            // ciliPanel.addEventListener('load', function (event){
            //     resizeFrame();
            // });

        }else if (selTab == 3){
            // 增加预览图
            ciliPanel.classList.add('hide');
            preImageDiv.classList.remove('hide');
            preImageDiv.innerHTML = '';
            ciliPanel.innerHTML = '';
            searchFileList(false, newCode, 'preview', preImgCallback, finishCallback, infoCallback);

        }else if (selTab == 4){
            longImageDiv.innerHTML = '';
            searchFileList(false, avcode, 'longimg', longImgCallback);
        }


        function preImgCallback(ret, imgName){
            if (ret == 1) {
                let avcode_00 = formatCodeFor00(newCode);
                previewUrl = `https://spic.hotoss.com/dmm/digital/video/${avcode_00}/${avcode_00}jp-${imgName}.jpg`;

            } else if (ret == 2) {
                previewUrl = imgName;

            } else if (ret == 0) {
                previewUrl = `http://localhost:10168/preview/${imgName}`;

            } else {
                previewUrl = `http://localhost:10168/preview/error.jpg`;
            }

            let previewImg = document.createElement('img');
            previewImg.classList.add('preview-img');
            previewImg.classList.add('lazyload');
            previewImg.dataset.src = previewUrl;
            previewImg.src = 'icons/img_loading.jpg';

            preImageDiv.appendChild(previewImg);

        }

        function ciliCallback(ret, rowHtml){
            if (ret == 0) {
                ciliPanel.innerHTML += rowHtml;

            } else {
                previewUrl = `http://localhost:10168/preview/error.jpg`;
                let previewImg = document.createElement('img');
                previewImg.classList.add('preview-img');
                previewImg.classList.add('lazyload');
                previewImg.dataset.src = previewUrl;
                previewImg.src = 'icons/img_loading.jpg';

                ciliPanel.appendChild(previewImg);
            }

        }

        function finishCallback(res) {
            // 监听滚动事件
            lazyLoadImages(scrollContent);

        }
        function infoCallback(labelObj) {
            label_code.textContent = labelObj.lable_code;
            label_ri.textContent = labelObj.lable_ri;
            label_zh.textContent = labelObj.lable_zh;
            label_shic.textContent = labelObj.lable_shic;
            label_yany.textContent = labelObj.lable_yany;
            label_jies.textContent = labelObj.lable_jies;
        }


        function longImgCallback(ret, imgName) {
            if (ret == 0) {
                previewUrl = `http://localhost:10168/longimg/${imgName}`;
            } else {
                previewUrl = `http://localhost:10168/longimg/error.jpg`;
            }

            let previewImg = document.createElement('img');
            previewImg.classList.add('prelong-img');
            previewImg.src = previewUrl;

            longImageDiv.appendChild(previewImg);
        }

    }

    function loadImage(img, filePath) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', filePath, true);
        xhr.responseType = 'blob';
        xhr.onload = function (e) {
            if (this.status === 200) {
                var blob = this.response;
                var reader = new FileReader();
                reader.onloadend = function () {
                    // var img = new Image();
                    img.src = reader.result;
                    // document.body.appendChild(img);
                };
                reader.readAsDataURL(blob);
            }
        };
        xhr.send();
    }

    function startRequest(avcode, fromStr) {
        let url = `http://localhost:10168/startrequest?avcode=${avcode}&fromstr=${fromStr}`;

        // 使用 fetch 发送 GET 请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON
                return ;
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
            });

    }

    // 懒加载逻辑
    function lazyLoadImages(scroolElement) {
        let lazyLoadThrottleTimeout;

        // 检查内容是否在可视窗口内
        function isInViewport(element) {
            let top = element.offsetTop - scrollContent.scrollTop;
            if (top < (window.innerHeight * 2)) {
                return true;
            }

            return false;
        }

        function lazyLoad() {
            if (lazyLoadThrottleTimeout) {
                clearTimeout(lazyLoadThrottleTimeout);
            }

            lazyLoadThrottleTimeout = setTimeout(function () {
                const images = document.querySelectorAll('.lazyload');
                images.forEach(img => {
                    if (img.src.includes('img_loading.jpg') && isInViewport(img)) {
                        // const source = img.getAttribute('data-src');
                        const source = img.dataset.src;
                        img.src = source;
                        // img.removeAttribute('data-src');
                        img.classList.remove('lazyload');
                    }
                });

                if (images.length == 0) {
                    scroolElement.removeEventListener("scroll", lazyLoad);
                    scroolElement.removeEventListener("resize", lazyLoad);
                    scroolElement.removeEventListener("orientationChange", lazyLoad);
                }
            }, 200);
        }

        lazyLoad();
        scroolElement.addEventListener("scroll", lazyLoad);
        scroolElement.addEventListener("resize", lazyLoad);
        scroolElement.addEventListener("orientationChange", lazyLoad);
    }
	
	// function resizeFrame(){
	// 	var iframeBody = ciliPanel.contentDocument || ciliPanel.contentWindow.document;
	//
	// 	var contentWidth = iframeBody.body.scrollWidth;
	// 	ciliPanel.style.Width = contentWidth + 'px';
	//
	// 	var contentHeight = iframeBody.body.scrollHeight;
	// 	ciliPanel.style.height = contentHeight + 'px';
	// }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region Common
    function formatCode(code) {
        let newCode = code;
        if (code.indexOf('-') == -1) {
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars) {
                newCode = chars[0] + "-" + numbers[0];
            }
        }

        return newCode;
    }

    function formatCodeForNone(code) {
        let newCode = code;
        let numbers = code.match(/\d+/g);
        let chars = code.match(/[a-zA-Z]+/g);

        if (numbers && chars) {
            newCode = chars[0] + "%20" + numbers[0];
        }

        return newCode;
    }

    function formatCodeFor00(code) {
        let newCode = code;
        let numbers = code.match(/\d+/g);
        let chars = code.match(/[a-zA-Z]+/g);

        if (numbers && chars) {
            newCode = chars[0] + "00" + numbers[0];
        }

        return newCode;
    }

    function splitSpan(str) {
        let splitArr = [];

        let index1 = -1;
        let matchs = str.match(/ |(---)/);
        if (matchs && matchs.index) {
            index1 = matchs.index;
        }

        if (index1 > 0) {
            splitArr.push(str.substring(0, index1));
        }

        let index2 = str.lastIndexOf('==');
        let index3 = -1;
        let matchs2 = str.match(/\.|(JavBus)|(JavDB)/);
        if (matchs2 && matchs2.index) {
            index3 = matchs2.index;
        }

        if (index2 > 0 && index3 > 0) {
            splitArr.push(str.substring(index1, index2));
            splitArr.push(str.substring(index2, index3));
        }
        if (index2 < 0 && index3 > 0) {
            splitArr.push(str.substring(index1, index3));
        }

        return splitArr;
    }

    function getSelectedText() {
        // 使用window.getSelection()获取Selection对象
        const selection = window.getSelection();

        // 检查是否有选择的文本
        if (selection.rangeCount > 0) {
            // 获取第一个（也可能是唯一的）Range对象
            const range = selection.getRangeAt(0);

            // 使用Range对象的toString方法获取选择的文本
            // 注意：这里假设选择的是纯文本，没有包含其他元素或富文本格式
            const selectedText = range.toString();

            // 返回选择的文本
            return selectedText;
        }

        // 如果没有选择的文本，返回null或空字符串
        return null; // 或者 return '';
    }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region TopTools

    function initTopPanel() {

        const colNum = document.getElementById('col-num');
        colNum.addEventListener('input', function (event) {
            let colNum = event.target.value;

            preImageDiv.style.gridTemplateColumns = `repeat(${colNum},auto)`;
        });

        // tab页切换
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabContents = document.querySelectorAll('.tab-content');
        tabButtons.forEach(button => {
            button.addEventListener('click', function () {
                const targetTab = this.getAttribute('data-tab');
                const targetIndex = this.getAttribute('data-index');

                // Hide all tab contents
                tabContents.forEach(content => {
                    content.style.display = 'none';
                });

                document.getElementById(targetTab).style.removeProperty('display');

                // Optionally, remove active class from all buttons and add to the clicked button
                tabButtons.forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');

                previewBookmark(targetIndex, selBookmark, null);
            });
        });

        copyRiBtn.addEventListener('click', function (event){
            let avName = label_code.textContent;
            let titleStr = label_ri.textContent;
            const selected = getSelectedText();
            if (selected) {
                titleStr = selected.trim();
            }
            avName += ' ' + titleStr;
            let nvYan = label_yany.textContent;
            if (nvYan){
                avName += '==' + nvYan;
            }

            // const textCopied = ClipboardJS.copy(codeStr + ' ' + titleStr + '==' + nvYan);
            navigator.clipboard.writeText(avName);
        });

        copyZhBtn.addEventListener('click', function (event){
            let avName = label_code.textContent;
            let titleStr = label_zh.textContent;
            const selected = getSelectedText();
            if (selected) {
                titleStr = selected.trim();
            }
            avName += ' ' + titleStr;
            let nvYan = label_yany.textContent;
            if (nvYan){
                avName += '==' + nvYan;
            }

            // const textCopied = ClipboardJS.copy(codeStr + ' ' + titleStr + '==' + nvYan);
            navigator.clipboard.writeText(avName);
        });

        addBookmarkBtn.addEventListener('click', function (event){
            if (selAvUrl){
                let bookmark = {
                    'parentId': '2108',
                    'title': titleSpan.textContent,
                    'url': selAvUrl
                };
                chrome.bookmarks.create(bookmark, function (result){
                    console.log('add bookmark result: ' + result);
                    alert('add bookmark result: ' + result);
                });
            }

            event.stopPropagation();
        });
		
		randmBtn.addEventListener('click', function(event){
			if (!selNodes) return;

            randmNodes.children = [];
            let nodeLen = selNodes[0].children.length;
            for (let i=0; i<20; i++){
                let index = Math.floor(Math.random() * nodeLen);
                randmNodes.children[i] = selNodes[0].children[index];
            }

            updateFileList(randmNodes.children);
			
		});
		
		randmPlayBtn.addEventListener('click', function(event){
			let liEles = fileList.querySelectorAll('li');
			if (!liEles) return;
			
			let liLen = liEles.length;
			let index = Math.floor(Math.random() * liLen);
			
			let randmLi = liEles[index];
			if (!randmLi) return;
			
			randmLi.scrollIntoView({ behavior: "smooth" });
			
			// 创建一个新的鼠标双击事件
			var dblClickEvent = new MouseEvent('dblclick', {
				view: window,
				bubbles: true,
				cancelable: true
			});
		 
			// 模拟双击
			randmLi.dispatchEvent(dblClickEvent);
			
		});
		

    }

    //#endregion

    // ******************************************************************************************************************************************************
    //#region histroy
	
    function loadHistory() {
        const history = JSON.parse(localStorage.getItem('inputHistory')) || [];
        historyList.innerHTML = ''; // Clear previous options
        history.forEach((item, index) => {
            const option = document.createElement('option');
            option.value = item;
			option.className = 'my-option';
            historyList.appendChild(option);
        });
    }

    function saveHistory(history) {
        localStorage.setItem('inputHistory', JSON.stringify(history));
    }

    function addHistory(newValue) {
        let history = JSON.parse(localStorage.getItem('inputHistory')) || [];
        const trimmedValue = newValue.trim();

        // Remove duplicates and trim empty strings
        history = history.filter(item => item.trim() !== '');
        history = [...new Set(history.map(item => item.trim()))];

        // Add new value if it's not already in the history
        // if (trimmedValue && !history.includes(trimmedValue)) {
            // history.unshift(trimmedValue); // Add to the beginning
            // if (history.length > 100) { // Limit the history size
                // history.pop(); // Remove the last item
            // }
        // }
		
		// 添加元素，如果存在则位置提前
		if (trimmedValue){
			let index = history.indexOf(trimmedValue);
			if (index !== -1) {
				// 移除元素
				history.splice(index, 1);
			}
			
			// 将元素添加到数组开头
			history.unshift(trimmedValue);
			if (history.length > 500) { // Limit the history size
                history.pop(); // Remove the last item
            }
		}

        saveHistory(history);
        // loadHistory(); // Reload the datalist options
    }
	
	function delHistory(delValue) {
        let history = JSON.parse(localStorage.getItem('inputHistory')) || [];
        // const trimmedValue = newValue.trim();

        // Remove duplicates and trim empty strings
        history = history.filter(item => item.trim() != delValue.trim());
		// history.splice(delValue, delValue - 1);

        saveHistory(history);
        // loadHistory(); // Reload the datalist options
    }
	
	// document.addEventListener('keydown', function (event) {
		// if (event.key == 'Delete' && event.target.matches('input')){
			// const selectedIndex = historyList.selectedIndex;
			// if (selectedIndex >= 0) {
				// historyList.remove(selectedIndex);
				// delHistory(selectedIndex)
			// }
			
		// }
    // });
	
	searchTxt.addEventListener('focus', function() {
	  // 焦点获取后执行的代码
	  loadHistory();
	  
	});

    searchTxt.addEventListener('blur', function () {
        addHistory(searchTxt.value);
    });
	
	searchTxt.addEventListener('input', function (event) {
		let searchStr = event.target.value;
		
		clearTimeout(inputTimer);
		inputTimer = setTimeout(function () {
			searchBookmarkList(searchStr);
		}, 1000);

	});
	
	clearSearchBtn.addEventListener('click', function () {
		searchTxt.value = '';
    });
	
	delSearchBtn.addEventListener('click', function () {
		let delValue = searchTxt.value;
		
		delHistory(delValue);
		searchTxt.value = '';
    });

    coverBtn.addEventListener('click', function (){
        if (coverImg.style.display === 'none'){
            coverImg.style.display = 'block';
            coverBtn.textContent = '播放';
        }else {
            coverImg.style.display = 'none';
            coverBtn.textContent = '封面';
        }
    });

    //#endregion

    function main() {

        // 读取书签
        chrome.bookmarks.getTree((treeNodes) => {
            let avold = findDestFolder(treeNodes[0].children);
            if (!avold) return;

            const rootUl = buildFolderTree2(avold.children);
            folderTree.appendChild(rootUl);
            // updateFileList(treeNodes[0].children[0].id); // Default to the first folder
        });

        initTopPanel();

    }

    main();
});